package com.imy.touch.root.shell;

import com.imy.common.util.CommandResult;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;

public class ShellCommand {

  public static volatile ShellCommand shellCommand = new ShellCommand();

  public static ShellCommand get() {
    return shellCommand;
  }

  Process process = null;
  private DataOutputStream os;

  public static final String COMMAND_SU = "su";
  public static final String COMMAND_SH = "sh";
  public static final String COMMAND_EXIT = "exit\n";
  public static final String COMMAND_LINE_END = "\n";

  private ShellCommand() {

  }

  public CommandResult execCommand(String command) {
    return execCommand(command,true);
  }

  public CommandResult execCommand(String command, boolean needResult) {
    int result = -1;
    BufferedReader successResult = null;
    BufferedReader errorResult = null;
    StringBuilder successMsg = null;
    StringBuilder errorMsg = null;
    try {
      if (process == null) {
        process = Runtime.getRuntime().exec(COMMAND_SU);
        os = new DataOutputStream(process.getOutputStream());
      }
      os.write(command.getBytes());
      os.writeBytes(COMMAND_LINE_END);
      os.flush();

      result = process.waitFor();
      // get command result
      if (needResult) {
        successMsg = new StringBuilder();
        errorMsg = new StringBuilder();
        successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
        errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String s;
        while ((s = successResult.readLine()) != null) {
          successMsg.append(s);
        }
        while ((s = errorResult.readLine()) != null) {
          errorMsg.append(s);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (successResult != null) {
          successResult.close();
        }
        if (errorResult != null) {
          errorResult.close();
        }
      } catch (Exception e) {

      }
    }
    return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null
        : errorMsg.toString());

  }
}
